/**
 * @namespace
 */
$.aws.keygrabber = {
	/**
	 * Sets handlers to detect when user presses keys. Handlers checks if system should be notified of particular event, and, if so, sends those notifications. 
	 * Also deals with crossbrowser inconsistentcy.
	 */
	init: function() {
		// Webkit detects 8 only on keyup/keydown. Opera detects it on keypress and keyup/keydown, but lets prevent default action only on keypress.
		// IE detects 13 only on keyup/keydown.
		$(document).keydown(function(e) {
			if ($.aws.keygrabber.targetAndModifiersOk(e) && e.keyCode == 8 && !$.browser.opera || $.aws.keygrabber.targetAndModifiersOk(e) && $.browser.msie && e.keyCode == 13) {
				$.aws.observer.notify('keypress', [e.keyCode, e]);
			}
		});
		$(document).keypress(function(e) {
			if ($.aws.keygrabber.targetAndModifiersOk(e) && e.keyCode != 8 || $.aws.keygrabber.targetAndModifiersOk(e) && e.keyCode == 8 && $.browser.opera) {
				$.aws.observer.notify('keypress', [e.charCode || e.keyCode, e]);
			}
		});
		$.aws.keygrabber.initiated = true;
	},
	/**
	 * Checks if event didn't come from form elements and no key modifiers were pressed
	 * @param {Object} e
	 */
	targetAndModifiersOk: function(e) {
		return !($(e.target).is('input') || $(e.target).is('textarea') || e.ctrlKey || e.altKey);
	}
};

/** Module should be initialized on global init event */
$.aws.observer.subscribe('init', 'init-keygrabber', $.aws.keygrabber.init);
